/*
   Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

*/

#include "AcceptorListenerTester.hpp"


AcceptorListenerTester::AcceptorListenerTester(){
	this->reset();
}

AcceptorListenerTester::~AcceptorListenerTester() {
	this->notifyWaiter();
	reset();
	closeConnections();
}

void AcceptorListenerTester::onAccepted(IConnection* poConnection) throw() {
	// Store new connection at list to deallocate memory
	boost::mutex::scoped_lock oScopedLock(m_mxConnections);
	poConnection->addRef();
	m_aConnections.push_back( poConnection );
	poConnection->addConnectionListener ( &m_oConnectionListener );
	poConnection->addStreamListener ( &m_oConnectionListener );

	// Add notification event
	this->m_bAccepted = true;
	this->notifyWaiter();
}

void AcceptorListenerTester::reset() {
	m_nLastErrorCode = 0;
	m_bAccepted = false;
}

bool AcceptorListenerTester::isAccepted() {
	return m_bAccepted;
}

boost::mutex& AcceptorListenerTester::getMonitor() {
	return m_mxMonitor;
}

void AcceptorListenerTester::waitForAnyEvent(boost::mutex::scoped_lock& oLock, const std::string& sLocation /*= "Unknown location"*/) {
	boost::xtime oXt;
	boost::xtime_get(&oXt, boost::TIME_UTC);
	oXt.sec += 10; // 5 sec is max await time
	if(!m_evAwait.timed_wait(oLock,oXt)) {
		std::cout << "Timeout for waiting accept event! Location: " << sLocation <<std::endl;
		throw SystemException("Timeout for waiting accept event! Location: " + sLocation);
	}
}

void AcceptorListenerTester::notifyWaiter() {
	boost::mutex::scoped_lock oLock(m_mxMonitor);
	m_evAwait.notify_one();
}

void AcceptorListenerTester::closeConnections(){

	// Close all connections
	boost::mutex::scoped_lock oScopedLock(m_mxConnections);
	foreach ( IConnection* poConnection, m_aConnections ) {
		poConnection->release();
	}
	m_aConnections.clear();
}

AcceptorListenerTester::Connections& AcceptorListenerTester::getConnections(){
	return this->m_aConnections;
}

ConnectionListenerTester& AcceptorListenerTester::getConnectionListener() {
	return m_oConnectionListener;
}
